<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <meta http-equiv="X-UA-Compatible" content="ie=edge">
    <title>Document</title>
    <script src="./js/vue.js"></script>
    <style>
        img {
            width: 500px;
            height: 300px;
            border: 1px solid red;
        }
        div{
            width: 500px;
            height: 300px;
            background-image: url('./img/loading.gif');
            background-repeat:no-repeat;
            background-position: center;
        }
    </style>
    <!-- object-fit 设置图片状态-->
    <!-- object-position  设置图片位置 -->

</head>

<body>
    <!-- <img id="img" src="./img/loading.gif" data-img="http://ps3.tgbus.com/uploadfiles/201101/20110104102301111.jpg" alt=""> -->
    <!-- <img src="http://ps3.tgbus.com/uploadfiles/201101/20110104102301111.jpg " alt=""> -->

    <div id="app">
        <img id="img" v-preload=" imgSrc ">
        <img id="img" v-preload=" imgSrc " src="./img/5-121204193934-51.gif">
        <img id="img" v-preload=" imgSrc " src="./img/07093129-1-CN1.gif">
        <div v-other=" imgSrc " id="" :style="{backgroundImage: 'url(./img/loading.gif)'}"></div>
    </div>
</body>
<script>
    /*
        图片预加载
        目的：在网络状况较差的的情况下，使用大小较小的loading图片提示用户正在加载
        原理：img标签的src属性或主动发送图片加载请求，在JS中隐藏的完成图片加载浏览
            器相同地址图片只会完成一次强求， 其他位置会直接读取缓存

    */
    /*
    function  preload(el){
        var imgDom = new Image();
        var imgSrc = el.getAttribute("data-img");
        imgDom.src = imgSrc;
        // console.log(imgDom);
        imgDom.onload = function(){
            el.src = imgSrc;
        }
    }
    preload(document.getElementById("img"));
    */
    Vue.directive("other", function (el, binding){
        var divDom = document.createElement("div");
        
    })
    Vue.directive("preload", function (el, binding) {
        var imgDom = new Image();
        if (el.src == "") {
            el.src = "";
        }
        el.style.objectFit = "none";
        imgDom.src = binding.value;
        imgDom.onload = function () {
            el.src = binding.value;
            el.style.objectFit = "";
        }
    });
    new Vue({
        el: "#app",
        data: {
            imgSrc: "http://ps3.tgbus.com/uploadfiles/201101/20110104102301111.jpg"
        },
    })
</script>

</html>